package cbfg.popup

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.fragment.app.DialogFragment

/**
 * 添加人：  Tom Hawk
 * 添加时间：2020/3/6 16:54
 * 功能描述：所见即所得的 DialogFragment
 * 参考：https://juejin.im/post/6844903635122388999
 */
open class BDialogFragment : DialogFragment() {
    companion object {
        private const val ARG_LAYOUT = "layout"
    }

    protected var mLayoutRes = 0

    /**
     * 外部传入的数据要进行保存，以免屏幕转换重新创建等情况找不到
     */
    fun setLayoutRes(@LayoutRes layoutRes: Int) {
        this.mLayoutRes = layoutRes
        val args = arguments ?: Bundle().also { arguments = it }
        args.putInt(ARG_LAYOUT, layoutRes)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (mLayoutRes == 0) {
            arguments?.run { mLayoutRes = this.getInt(ARG_LAYOUT) }
        }
        if (mLayoutRes != 0 && theme == 0) {
            setStyle(STYLE_NORMAL, R.style.Popup_NormalTheme)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return if (mLayoutRes == 0) {
            super.onCreateView(inflater, container, savedInstanceState)
        } else DFrameLayout(requireContext()).also {
            it.layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            it.setOnTouchOutsideListener {
                if (isCancelable) {
                    dismiss()
                }
            }
            inflater.inflate(mLayoutRes, it, true)
        }
    }
}